package pl.pawluk.inz.web;

import org.primefaces.event.SelectEvent;
import org.primefaces.event.UnselectEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import pl.pawluk.inz.dao.ICourseService;
import pl.pawluk.inz.dto.CourseDTO;
import pl.pawluk.inz.web.model.SelectableListDataModel;

import javax.faces.model.ListDataModel;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: mandp
 * Date: 23.05.13
 * Time: 14:55
 * To change this template use File | Settings | File Templates.
 */
@Component
@Scope("session")
public class CoursesBean extends BaseBean {

    @Autowired
    private LoginInfoBean loginInfoBean;

    @Autowired
    private ICourseService courseService;

    private CourseDTO course;


    public CourseDTO getCourse() {
        return course == null ? course = new CourseDTO() : course;
    }

    public void setCourse(CourseDTO course) {
        this.course = course;
    }

    public ListDataModel<CourseDTO> getCourses() {
        return new SelectableListDataModel<CourseDTO>(courseService.getAll());
    }

    public List<CourseDTO> getCoursesList() {
        return courseService.getAll();
    }


    @Override
    protected void insertOrUpdate() {
        if (course.getId() != null) {
            courseService.update(course);
        } else {
            courseService.create(course);
        }
    }

    @Override
    public void onRowUnselect(UnselectEvent event) {
        course = null;
    }

    @Override
    public void onRowSelect(SelectEvent event) {
        course = (CourseDTO) event.getObject();
    }

    @Override
    public void createNew() {
        course = null;
    }

    @Override
    public void delete() {
        courseService.delete(course);
    }
}
